package com.yjb.tenet.boot.system.infrastructure.log;

import cn.hutool.core.util.URLUtil;
import cn.hutool.extra.servlet.ServletUtil;
import cn.hutool.http.HttpUtil;
import com.yjb.tenet.boot.framework.satoken.core.LoginUser;
import com.yjb.tenet.boot.framework.satoken.core.utils.SecurityFrameworkUtils;
import com.yjb.tenet.boot.system.domain.entity.SysLog;
import com.yjb.tenet.boot.system.infrastructure.enums.ResultEnums;
import lombok.SneakyThrows;
import lombok.extern.slf4j.Slf4j;
import org.aspectj.lang.ProceedingJoinPoint;
import org.aspectj.lang.annotation.Around;
import org.aspectj.lang.annotation.Aspect;
import org.springframework.context.ApplicationEventPublisher;
import org.springframework.http.HttpHeaders;
import org.springframework.stereotype.Component;
import org.springframework.web.context.request.RequestContextHolder;
import org.springframework.web.context.request.ServletRequestAttributes;

import javax.annotation.Resource;
import javax.servlet.http.HttpServletRequest;
import java.util.Objects;

/**
 * @description 
 * @author yinjinbiao
 * @create 2022/5/23 14:35
 * @version 1.0
 */
@Aspect
@Component
@Slf4j
public class SysLogAspect {

	@Resource
	private ApplicationEventPublisher applicationEventPublisher;

	@Around("@annotation(log)")
	@SneakyThrows
	public Object around(ProceedingJoinPoint point, Log log) {
		SysLog logVo = getSysLog();
		logVo.setTitle(log.value());

		// 发送异步日志事件
		Long startTime = System.currentTimeMillis();
		Object obj;

		try {
			obj = point.proceed();
		}
		catch (Exception e) {
			logVo.setType(ResultEnums.FAIL.getValue());
			logVo.setException(e.getMessage());
			throw e;
		}
		finally {
			Long endTime = System.currentTimeMillis();
			logVo.setTime(endTime - startTime);
			applicationEventPublisher.publishEvent(new SysLogEvent(logVo));
		}

		return obj;
	}

	private SysLog getSysLog() {
		HttpServletRequest request = ((ServletRequestAttributes) Objects
				.requireNonNull(RequestContextHolder.getRequestAttributes())).getRequest();
		SysLog sysLog = new SysLog();
		sysLog.setCreateBy(Objects.requireNonNull(getUsername()));
		sysLog.setType(ResultEnums.SUCCESS.getValue());
		sysLog.setIp(ServletUtil.getClientIP(request));
		sysLog.setRequestUri(URLUtil.getPath(request.getRequestURI()));
		sysLog.setMethod(request.getMethod());
		sysLog.setUserAgent(request.getHeader(HttpHeaders.USER_AGENT));
		sysLog.setParams(HttpUtil.toParams(request.getParameterMap()));
		return sysLog;
	}

	/**
	 * 获取用户名称
	 * @return username
	 */
	private String getUsername() {
		LoginUser loginUser = SecurityFrameworkUtils.getLoginUser();
		return loginUser.getUsername();
	}


}
